package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.entity.BackResponseEntity;
import com.example.demo.entity.BooksInformation;
import com.example.demo.entity.Chapter;
import com.example.demo.entity.requestJson.AInsertChapterReq;
import com.example.demo.entity.requestJson.ALockChapterReq;
import com.example.demo.entity.requestJson.DeleteReq;
import com.example.demo.entity.responseJson.AllChapterToBookRes;
import com.example.demo.entity.responseJson.ChapterContentRes;
import com.example.demo.entity.responseJson.ListResult;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.BooksInformationMapper;
import com.example.demo.mapper.ChapterMapper;
import com.example.demo.service.AChapterService;
import com.example.demo.tools.UeditorUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 杨丽辉
 * @date : 2021/3/4 17:06
 * @description:
 */
@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class AChapterServiceImpl implements AChapterService {
    @Autowired
    private ChapterMapper chapterMapper;
    @Autowired
    private BooksInformationMapper booksInformationMapper;
    @Autowired
    private UeditorUtil ueditorUtil;

    /**
     * 更新新章节内容（新增）
     * */
    @Override
    public BackResponseEntity<Object> insertChapter(AInsertChapterReq aInsertChapterReq){
        String name = null;
        String id = null;
        String content = null;
        String words = null;
        Integer segment = null;
        Integer chapterContentCount = null;

        if(!ObjectUtils.isEmpty(aInsertChapterReq.getChapterName())){
            name = aInsertChapterReq.getChapterName()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(aInsertChapterReq.getBookId())){
            id = aInsertChapterReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(aInsertChapterReq.getChapterContent())){
            content = aInsertChapterReq.getChapterContent()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(aInsertChapterReq.getAuthorWords())){
            words = aInsertChapterReq.getAuthorWords()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(aInsertChapterReq.getSegment())){
            segment = aInsertChapterReq.getSegment();
        }
        if(!ObjectUtils.isEmpty(aInsertChapterReq.getChapterContent())){
            chapterContentCount = aInsertChapterReq.getChapterContentCount();
        }
        if(ObjectUtils.isEmpty(name) || ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(content) || ObjectUtils.isEmpty(words)
          || ObjectUtils.isEmpty(segment)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        if(chapterContentCount < 30){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1026, "文本内容不能少于100字");
        }
        if(chapterContentCount > 15000){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1027, "文本内容不能多于15000字");
        }

        Chapter chapter = new Chapter();
        chapter.setChapterName(name);
        chapter.setBookId(id);
        chapter.setChapterContent(content);
        chapter.setUpdateTime(LocalDateTime.now());
        chapter.setAuthorWords(words);
        chapter.setSegment(segment);
        chapter.setChapterContentCount(chapterContentCount);
        chapter.setLockStatus(0);
        chapter.setChapterCommentCount(0);
        chapter.setIsFree(aInsertChapterReq.getIsFree());
        if(aInsertChapterReq.getIsFree() == 1){
            chapter.setChapterPoints(chapterContentCount/400);
        }else {
            chapter.setChapterPoints(0);
        }

        LambdaUpdateWrapper<BooksInformation> wrapper = new UpdateWrapper<BooksInformation>().lambda();
        wrapper.eq(!ObjectUtils.isEmpty(id),BooksInformation::getBooksId,id)
                .set(!ObjectUtils.isEmpty(name),BooksInformation::getNewChaptername,name)
                .set(BooksInformation::getNewChapterUtime,LocalDateTime.now());

        int m = booksInformationMapper.update(null,wrapper);
        int i = chapterMapper.insert(chapter);

        if(i > 0 && m > 0){
            return  BackResponseEntity.success(ErrCodeEnum.unknown_0, "更新新章节内容成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1028, "更新新章节内容失败");
        }

    }

    /**
     * 查询一本书的所有章节
     * 根据返回的锁定状态跳转到不同页面
     * 如果未锁定，则调用queryChapterContent接口
     * 如果锁定，则前端自己写个页面跳转，提醒用户此章节已锁定，不能查看内容
     */
    @Override
    public BackResponseEntity<ListResult<List<AllChapterToBookRes>>> queryAllChapter(DeleteReq deleteReq){
        String id = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            id = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(id)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        Chapter chapter = new Chapter();
        chapter.setBookId(id);
        LambdaQueryWrapper<Chapter> queryWrapper = new QueryWrapper<Chapter>().lambda();
        queryWrapper.select(Chapter::getChapterName,Chapter::getUpdateTime,Chapter::getChapterId,Chapter::getLockStatus)
                .eq(!ObjectUtils.isEmpty(id),Chapter::getBookId,id);
        long count = PageHelper.count(() -> chapterMapper.selectList(queryWrapper));

        List<Chapter> list = chapterMapper.selectList(queryWrapper);
        List presenter = list;
        List<AllChapterToBookRes> res1 =presenter;
        ListResult<List<AllChapterToBookRes>> listResult = new ListResult((int)count, res1);

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult, "");
    }

    /**
     * 查看章节是否免费
     * */
    /**
     * 查看章节内容(免费和购买章节之后)
     * 锁定章节内容不能查看
     */
    @Override
    public BackResponseEntity<List<ChapterContentRes>> queryChapterContent(DeleteReq deleteReq){
        String id = null;
        Integer locktatus = chapterMapper.selectById(deleteReq.getId()).getLockStatus();
        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            id = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(id)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        if(locktatus == 1){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1051, "帖子已锁定");
        }

        Chapter chapter = new Chapter();
        chapter.setBookId(id);
        LambdaQueryWrapper<Chapter> queryWrapper = new QueryWrapper<Chapter>().lambda();
        queryWrapper.select(Chapter::getChapterId,Chapter::getChapterName,Chapter::getChapterContent,Chapter::getChapterCommentCount,Chapter::getAuthorWords)
                .eq(!ObjectUtils.isEmpty(id),Chapter::getChapterId,id)
                .eq(Chapter::getLockStatus,0);

        List<Chapter> list = chapterMapper.selectList(queryWrapper);
        List<ChapterContentRes> res = new ArrayList<>();
        List presenter = list;
        List<ChapterContentRes> res1 =presenter;

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, res1, "");
    }

     /**
      * 作者锁定章节
      * */
    @Override
    public BackResponseEntity<Object> lockChapter(ALockChapterReq aLockChapterReq){
        String id = null;
        Integer status = 0;

        if(!ObjectUtils.isEmpty(aLockChapterReq.getChapterId())){
            id = aLockChapterReq.getChapterId();
        }
        if(!ObjectUtils.isEmpty(aLockChapterReq.getLockStatus())){
            status = aLockChapterReq.getLockStatus();
        }

        if(ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(status)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        LambdaUpdateWrapper<Chapter> wrapper = new UpdateWrapper<Chapter>().lambda();
        wrapper.eq(!ObjectUtils.isEmpty(id),Chapter::getChapterId,id)
                .set(!ObjectUtils.isEmpty(status),Chapter::getLockStatus,status);

        int i = chapterMapper.update(null,wrapper);

        if(i > 0){
            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "章节锁定成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1039, "章节锁定失败");
        }

    }

    /**
     * 修改章节内容
     * */
    @Override
    public BackResponseEntity<Object> updateChapter(AInsertChapterReq aInsertChapterReq) {
        String name = null;
        String id = null;
        String content = null;
        String words = null;
        Integer segment = null;

        if (!ObjectUtils.isEmpty(aInsertChapterReq.getChapterName())) {
            name = aInsertChapterReq.getChapterName()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(aInsertChapterReq.getChapterId())) {
            id = aInsertChapterReq.getChapterId()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(aInsertChapterReq.getChapterContent())) {
            content = aInsertChapterReq.getChapterContent()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(aInsertChapterReq.getAuthorWords())) {
            words = aInsertChapterReq.getAuthorWords()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(aInsertChapterReq.getSegment())) {
            segment = aInsertChapterReq.getSegment();
        }

        if (ObjectUtils.isEmpty(id)) {
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        if(!ObjectUtils.isEmpty(content)){
            if (content.length() < 30) {
                return BackResponseEntity.success(ErrCodeEnum.unknown_1026, "文本内容不能少于100字");
            }
            if (content.length() > 15000) {
                return BackResponseEntity.success(ErrCodeEnum.unknown_1027, "文本内容不能多于15000字");
            }
        }

        Chapter chapter = new Chapter();
        chapter.setChapterName(name);
        chapter.setChapterId(id);
        chapter.setChapterContent(content);
        chapter.setModifyTime(LocalDateTime.now());
        chapter.setAuthorWords(words);
        chapter.setSegment(segment);


        int i = chapterMapper.updateById(chapter);

        if (i > 0) {
            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "修改章节内容成功");
        } else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1028, "修改章节内容失败");
        }
    }
}
